package rmi.server;

import java.util.ArrayList;
import java.util.GregorianCalendar;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import model.MessageInterface;
import model.UserInterface;

public class MessageRemote extends Remote implements Message
{
	private static MessageRemote instance;
	
	public static MessageRemote getInstance()
	{
		if (instance == null)
		{
			instance = new MessageRemote();
		}
		
		return instance;
	}
	
	private MessageRemote()
	{
		
	}
	
	final protected Object clone()
	{
		return null;
	}
	
	public MessageInterface newMessage(UserInterface user)
	{
		return new model.Message(user);
	}
	
	public UserInterface getRecipient(String username)
	{
		Query getRecipient = entityManager.createQuery("SELECT user FROM User user WHERE username = :username");
		
		getRecipient.setParameter("username", username);
		
		try
		{
			return (UserInterface) getRecipient.getSingleResult();
		}
		catch (NoResultException e)
		{
			return null;
		}
	}
	
	public void storeMessage(MessageInterface message)
	{
		// When the mail was sent.
		message.setDate(new GregorianCalendar());
		
		storeEntity(message);
	}

	public void deleteMessage(MessageInterface message)
	{
		removeEntity(message);
	}
	
	public ArrayList<MessageInterface> getMessages(UserInterface player)
	{
		Query getMessages = entityManager.createQuery("SELECT message FROM Message message WHERE to = :to");
		
		getMessages.setParameter("to", player);
		
		return (ArrayList<MessageInterface>) getMessages.getResultList();
	}
}
